<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交易策略回测系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            padding-bottom: 60px;
        }
        
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .subtitle {
            opacity: 0.9;
            font-size: 14px;
        }
        
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 2px solid #e0e0e0;
        }
        
        .tab {
            padding: 12px 24px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 16px;
            color: #666;
            border-bottom: 3px solid transparent;
            transition: all 0.3s;
        }
        
        .tab:hover {
            color: #667eea;
        }
        
        .tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }
        
        .tab-content {
            display: none;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
        }
        
        input, select, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .btn-danger {
            background: #f56565;
            color: white;
        }
        
        .btn-danger:hover {
            background: #e53e3e;
        }
        
        .btn-secondary {
            background: #718096;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4a5568;
        }
        
        .output-container {
            background: #1e1e1e;
            color: #d4d4d4;
            padding: 20px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            max-height: 500px;
            overflow-y: auto;
            margin-top: 20px;
            white-space: pre-wrap;
        }
        
        .webui-frame {
            width: 100%;
            height: 800px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-top: 20px;
            margin-bottom: 40px;
        }
        
        .results-grid {
            display: grid;
            gap: 20px;
            margin-top: 20px;
        }
        
        .result-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .result-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .result-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .result-date {
            font-size: 12px;
            color: #999;
        }
        
        .result-metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
        }
        
        .metric {
            text-align: center;
        }
        
        .metric-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }
        
        .metric-value {
            font-size: 20px;
            font-weight: 600;
        }
        
        .metric-value.positive {
            color: #48bb78;
        }
        
        .metric-value.negative {
            color: #f56565;
        }
        
        .chart-container {
            margin-top: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-running {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-completed {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-error {
            background: #fee2e2;
            color: #991b1b;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>🚀 交易策略回测系统</h1>
            <p class="subtitle">配置参数、运行回测、分析结果 - 一站式量化交易回测平台</p>
        </header>
        
        <div class="tabs">
            <button class="tab active" onclick="switchTab('run')">运行回测</button>
            <button class="tab" onclick="switchTab('history')">历史结果</button>
            <button class="tab" onclick="switchTab('compare')">参数对比</button>
        </div>
        
        <!-- 运行回测标签页 -->
        <div id="tab-run" class="tab-content active">
            <h2 style="margin-bottom: 20px;">配置回测参数</h2>
            
            <div class="form-group">
                <label>选择策略</label>
                <select id="strategy-select" onchange="loadStrategyParams()">
                    <option value="">-- 请选择策略 --</option>
                </select>
            </div>
            
            <div id="params-form"></div>
            
            <div style="display: flex; gap: 10px; margin-top: 20px;">
                <button class="btn btn-primary" onclick="runBacktest()">开始回测</button>
                <button class="btn btn-danger" onclick="stopBacktest()">停止回测</button>
                <button class="btn btn-secondary" onclick="clearOutput()">清空输出</button>
            </div>
            
            <h3 style="margin-top: 30px; margin-bottom: 10px;">实时输出</h3>
            <div id="output" class="output-container">等待运行...</div>
            
            <h3 style="margin-top: 30px; margin-bottom: 10px;">TqSDK Web UI <span id="webui-port-info" style="font-size: 14px; color: #999;"></span></h3>
            <iframe id="webui-frame" class="webui-frame" src="about:blank"></iframe>
            <div id="webui-loading" style="text-align: center; padding: 40px; color: #999; display: none;">
                等待回测启动...
            </div>
        </div>
        
        <!-- 历史结果标签页 -->
        <div id="tab-history" class="tab-content">
            <h2 style="margin-bottom: 20px;">历史回测结果</h2>
            
            <div class="form-row" style="margin-bottom: 20px;">
                <div class="form-group">
                    <label>筛选策略</label>
                    <select id="history-strategy-filter" onchange="loadHistory()">
                        <option value="">全部策略</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>显示数量</label>
                    <select id="history-limit" onchange="loadHistory()">
                        <option value="20">20条</option>
                        <option value="50" selected>50条</option>
                        <option value="100">100条</option>
                    </select>
                </div>
            </div>
            
            <div id="history-results" class="results-grid"></div>
        </div>
        
        <!-- 参数对比标签页 -->
        <div id="tab-compare" class="tab-content">
            <h2 style="margin-bottom: 20px;">参数对比分析</h2>
            
            <div class="form-group">
                <label>选择策略</label>
                <select id="compare-strategy-select" onchange="loadCompareData()">
                    <option value="">-- 请选择策略 --</option>
                </select>
            </div>
            
            <div id="compare-chart" class="chart-container">
                <canvas id="compare-canvas"></canvas>
            </div>
            
            <div id="compare-table" style="margin-top: 20px; overflow-x: auto;"></div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script>
        let outputInterval = null;
        let compareChart = null;
        let currentWebuiPort = null;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadStrategies();
            loadHistory();
        });
        
        // 切换标签页
        function switchTab(tabName) {
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            event.target.classList.add('active');
            document.getElementById('tab-' + tabName).classList.add('active');
            
            if (tabName === 'history') {
                loadHistory();
            } else if (tabName === 'compare') {
                loadCompareData();
            }
        }
        
        // 加载策略列表
        async function loadStrategies() {
            const response = await fetch('/api/strategies');
            const strategies = await response.json();
            
            const select = document.getElementById('strategy-select');
            const historyFilter = document.getElementById('history-strategy-filter');
            const compareSelect = document.getElementById('compare-strategy-select');
            
            // 清空现有选项（保留第一个默认选项）
            while (select.options.length > 1) select.remove(1);
            while (historyFilter.options.length > 1) historyFilter.remove(1);
            while (compareSelect.options.length > 1) compareSelect.remove(1);
            
            strategies.forEach(strategy => {
                const option = new Option(strategy.name, strategy.id);
                select.add(option.cloneNode(true));
                historyFilter.add(option.cloneNode(true));
                compareSelect.add(option.cloneNode(true));
            });
        }
        
        // 加载策略参数
        async function loadStrategyParams() {
            const strategyId = document.getElementById('strategy-select').value;
            if (!strategyId) {
                document.getElementById('params-form').innerHTML = '';
                return;
            }
            
            const response = await fetch(`/api/strategy/${strategyId}/params`);
            const params = await response.json();
            
            let html = '<div class="form-row">';
            
            for (const [key, value] of Object.entries(params)) {
                html += `
                    <div class="form-group">
                        <label>${key}</label>
                        <input type="text" id="param-${key}" value="${value}">
                    </div>
                `;
            }
            
            html += '</div>';
            document.getElementById('params-form').innerHTML = html;
        }
        
        // 运行回测
        async function runBacktest() {
            const strategyId = document.getElementById('strategy-select').value;
            if (!strategyId) {
                alert('请先选择策略');
                return;
            }
            
            // 收集参数
            const params = {};
            document.querySelectorAll('[id^="param-"]').forEach(input => {
                const key = input.id.replace('param-', '');
                params[key] = input.value;
            });
            
            // 发送请求
            const response = await fetch('/api/backtest/run', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({strategy_id: strategyId, params: params})
            });
            
            const result = await response.json();
            
            if (result.success) {
                currentWebuiPort = result.webui_port;
                alert(`回测已启动\nWeb UI 端口: ${result.webui_port}`);
                
                // 显示加载提示
                document.getElementById('webui-frame').style.display = 'none';
                document.getElementById('webui-loading').style.display = 'block';
                document.getElementById('webui-port-info').textContent = `(端口: ${result.webui_port})`;
                
                // 延迟3秒后加载 Web UI（等待服务启动）
                setTimeout(() => {
                    updateWebuiFrame(result.webui_port);
                }, 3000);
                
                startOutputPolling();
            } else {
                alert('启动失败: ' + result.message);
            }
        }
        
        // 更新 Web UI iframe
        function updateWebuiFrame(port) {
            const frame = document.getElementById('webui-frame');
            const loading = document.getElementById('webui-loading');
            
            frame.src = `http://127.0.0.1:${port}`;
            frame.style.display = 'block';
            loading.style.display = 'none';
        }
        
        // 停止回测
        async function stopBacktest() {
            const response = await fetch('/api/backtest/stop', {method: 'POST'});
            const result = await response.json();
            alert(result.message);
            stopOutputPolling();
        }
        
        // 清空输出
        function clearOutput() {
            document.getElementById('output').textContent = '已清空...';
        }
        
        // 开始轮询输出
        function startOutputPolling() {
            if (outputInterval) return;
            
            outputInterval = setInterval(async () => {
                const response = await fetch('/api/backtest/output');
                const data = await response.json();
                document.getElementById('output').textContent = data.output;
                
                // 更新端口信息
                if (data.webui_port && data.webui_port !== currentWebuiPort) {
                    currentWebuiPort = data.webui_port;
                    document.getElementById('webui-port-info').textContent = `(端口: ${data.webui_port})`;
                }
                
                // 自动滚动到底部
                const output = document.getElementById('output');
                output.scrollTop = output.scrollHeight;
            }, 1000);
        }
        
        // 停止轮询输出
        function stopOutputPolling() {
            if (outputInterval) {
                clearInterval(outputInterval);
                outputInterval = null;
            }
        }
        
        // 加载历史结果
        async function loadHistory() {
            const strategyName = document.getElementById('history-strategy-filter').value;
            const limit = document.getElementById('history-limit').value;
            
            const response = await fetch(`/api/backtest/history?strategy_name=${strategyName}&limit=${limit}`);
            const results = await response.json();
            
            const container = document.getElementById('history-results');
            
            if (results.length === 0) {
                container.innerHTML = '<div class="loading">暂无回测结果</div>';
                return;
            }
            
            let html = '';
            results.forEach(result => {
                const returnClass = result.total_return >= 0 ? 'positive' : 'negative';
                const returnSign = result.total_return >= 0 ? '+' : '';
                
                html += `
                    <div class="result-card" onclick="viewDetail(${result.id})">
                        <div class="result-header">
                            <div class="result-title">${result.strategy_name} - ${result.symbol}</div>
                            <div class="result-date">${new Date(result.created_at).toLocaleString()}</div>
                        </div>
                        <div class="result-metrics">
                            <div class="metric">
                                <div class="metric-label">收益率</div>
                                <div class="metric-value ${returnClass}">${returnSign}${(result.total_return * 100).toFixed(2)}%</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">夏普率</div>
                                <div class="metric-value">${result.sharpe_ratio ? result.sharpe_ratio.toFixed(2) : 'N/A'}</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">最大回撤</div>
                                <div class="metric-value negative">${(result.max_drawdown * 100).toFixed(2)}%</div>
                            </div>
                            <div class="metric">
                                <div class="metric-label">胜率</div>
                                <div class="metric-value">${(result.winning_rate * 100).toFixed(2)}%</div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // 查看详情
        function viewDetail(backtestId) {
            window.open(`/detail.html?id=${backtestId}`, '_blank');
        }
        
        // 加载对比数据
        async function loadCompareData() {
            const strategyName = document.getElementById('compare-strategy-select').value;
            if (!strategyName) {
                document.getElementById('compare-chart').innerHTML = '<div class="loading">请选择策略</div>';
                document.getElementById('compare-table').innerHTML = '';
                return;
            }
            
            const response = await fetch(`/api/backtest/compare?strategy_name=${strategyName}`);
            const results = await response.json();
            
            if (results.length === 0) {
                document.getElementById('compare-chart').innerHTML = '<div class="loading">该策略暂无回测数据</div>';
                document.getElementById('compare-table').innerHTML = '';
                return;
            }
            
            // 绘制图表
            drawCompareChart(results);
            
            // 显示表格
            drawCompareTable(results);
        }
        
        // 绘制对比图表
        function drawCompareChart(results) {
            const ctx = document.getElementById('compare-canvas').getContext('2d');
            
            if (compareChart) {
                compareChart.destroy();
            }
            
            compareChart = new Chart(ctx, {
                type: 'scatter',
                data: {
                    datasets: [{
                        label: '收益率 vs 夏普率',
                        data: results.map(r => ({
                            x: r.sharpe_ratio || 0,
                            y: (r.total_return || 0) * 100,
                            id: r.id
                        })),
                        backgroundColor: 'rgba(102, 126, 234, 0.6)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        pointRadius: 8,
                        pointHoverRadius: 12
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: '回测结果对比 - 收益率 vs 夏普率'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `收益率: ${context.parsed.y.toFixed(2)}%, 夏普率: ${context.parsed.x.toFixed(2)}`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '夏普率'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '收益率 (%)'
                            }
                        }
                    }
                }
            });
        }
        
        // 绘制对比表格
        function drawCompareTable(results) {
            let html = '<table style="width: 100%; border-collapse: collapse;">';
            html += '<thead><tr style="background: #f5f7fa;">';
            html += '<th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">ID</th>';
            html += '<th style="padding: 12px; text-align: left; border-bottom: 2px solid #ddd;">时间</th>';
            html += '<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">收益率</th>';
            html += '<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">年化收益</th>';
            html += '<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">夏普率</th>';
            html += '<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">最大回撤</th>';
            html += '<th style="padding: 12px; text-align: right; border-bottom: 2px solid #ddd;">胜率</th>';
            html += '</tr></thead><tbody>';
            
            results.forEach((r, i) => {
                const bg = i % 2 === 0 ? '#fff' : '#f9fafb';
                html += `<tr style="background: ${bg};">`;
                html += `<td style="padding: 12px; border-bottom: 1px solid #eee;">${r.id}</td>`;
                html += `<td style="padding: 12px; border-bottom: 1px solid #eee;">${new Date(r.test_timestamp).toLocaleString()}</td>`;
                html += `<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">${((r.total_return || 0) * 100).toFixed(2)}%</td>`;
                html += `<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">${((r.annual_yield || 0) * 100).toFixed(2)}%</td>`;
                html += `<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">${(r.sharpe_ratio || 0).toFixed(2)}</td>`;
                html += `<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">${((r.max_drawdown || 0) * 100).toFixed(2)}%</td>`;
                html += `<td style="padding: 12px; text-align: right; border-bottom: 1px solid #eee;">${((r.winning_rate || 0) * 100).toFixed(2)}%</td>`;
                html += '</tr>';
            });
            
            html += '</tbody></table>';
            document.getElementById('compare-table').innerHTML = html;
        }
    </script>
</body>
</html>